<?php

namespace App\Request\auth\Service\Auth;

use App\Repository\Auth\MenuRepository;
use App\Request\auth\Service\IService;
use Hyperf\Collection\Collection;


/**
 * 后台菜单服务
 */
final class MenuService extends IService
{
    public function __construct(
        protected readonly MenuRepository $repository,
    )
    {
    }


    /**
     * 创建\编辑菜单
     * @param mixed $id
     * @param array $data
     * @return mixed
     */
    public function updateById(mixed $id, array $data): mixed
    {
        if ($id) {
            return parent::updateById($id, $data);
        }
        return $this->create($data);
    }


    /**
     * 删除菜单
     * @param mixed $id
     * @return int
     * @throws \Exception
     */
    public function deleteById(mixed $id): int
    {
        // 判断是否有子菜单
        if ($this->repository->getQuery()->where('parent_id', $id)->count()) {

            throw new \Exception('请先删除子菜单');
        }
        return parent::deleteById($id);
    }

    /**
     * 获取权限标识 按钮类权限
     * @param array|string $ids
     * @return array
     */
    public function getPermission(array|string $ids): array
    {
        return $this->repository->getQuery()
            ->where(["type" => 2, "status" => 1])
            ->when(is_array($ids) && $ids != "*", function ($query) use ($ids) {
                $query->whereIn('id', $ids);
            })
            ->pluck('permission')
            ->toArray();
    }


    /**
     * 获取菜单列表权限
     * @param array|string $menuIds
     * @return Collection
     */
    public function getMenus(array|string $menuIds): Collection
    {
        $filed = ['id', 'parent_id', 'name', 'path', 'component','type','icon','show_type','query'];
        // 获取所有菜单 超级管理员权限
        if ($menuIds == "*") return $this->repository->list(["type" => [0, 1], "status" => 1], $filed);
        //普通角色
        $data = $this->repository->list(["type" => [0, 1], "status" => 1, 'id' => $menuIds]);
        $tempMenuIds = $menuIds;
        foreach ($data as $item) {
            //判断是否是父节点
            if ($item->parent_id != 0) {
                $tempMenuIds[] = $item->parent_id;
            }
        }
        //去重
        $menuIds = array_unique($tempMenuIds);
        return $this->repository->list(['id' => $menuIds, 'type' => [0, 1]], $filed);
    }


}